package com.imax.center.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.excel.EasyExcel;
import com.imax.center.common.Result;
import com.imax.center.domain.HospitalSensorDataExcel;
import com.imax.center.service.StatisticsService;
import com.imax.center.service.impl.h3yun.H3yunOperate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

@Slf4j
@Service
public class StatisticsServiceImpl implements StatisticsService {

    @Autowired
    H3yunOperate h3yunOperate;


    @Override
    public Result<JSONObject> getBaseCount(String areaCode) {
        JSONObject params = new JSONObject();
        params.put("areaCode", areaCode);
        JSONObject bizObject = h3yunOperate.CustomInvoke("ApiStatistics", "getBaseCount", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<JSONObject> getCameraOnline(String areaCode) {
        JSONObject params = new JSONObject();
        params.put("areaCode", areaCode);
        JSONObject bizObject = h3yunOperate.CustomInvoke("ApiStatistics", "getCameraOnline", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<JSONArray> getOrgStatistics(String areaCode) {
        JSONObject params = new JSONObject();
        params.put("areaCode", areaCode);
        JSONArray list = h3yunOperate.CustomInvokeArray("ApiStatistics", "getOrgStatistics", params);
        return Result.success(list, "ok");
    }

    @Override
    public Result<JSONObject> getOrgMapStatistics(String areaCode) {
        JSONObject params = new JSONObject();
        params.put("areaCode", areaCode);
        JSONObject bizObject = h3yunOperate.CustomInvoke("ApiStatistics", "getOrgMapStatistics", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<JSONObject> getEventCount(JSONObject params) {
        JSONObject bizObject = h3yunOperate.CustomInvoke("EventStatistics", "getEventCount", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<JSONArray> get7DayAlarmCount(String areaCode) {
        JSONObject params = new JSONObject();
        params.put("areaCode", areaCode);
        JSONArray bizObject = h3yunOperate.CustomInvokeArray("EventStatistics", "get7DayAlarmCount", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<JSONArray> get1YearW00000RtdTrend(String areaCode) {
        JSONObject params = new JSONObject();
        params.put("areaCode", areaCode);
        JSONArray bizObject = h3yunOperate.CustomInvokeArray("EventStatistics", "get1YearW00000RtdTrend", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<JSONArray> get7DayTrendCount(String areaCode) {
        JSONObject params = new JSONObject();
        params.put("areaCode", areaCode);
        JSONArray bizObject = h3yunOperate.CustomInvokeArray("EventStatistics", "get7DayTrendCount", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<JSONArray> get7DayHandlerTrend(String areaCode) {
        JSONObject params = new JSONObject();
        params.put("areaCode", areaCode);
        JSONArray bizObject = h3yunOperate.CustomInvokeArray("EventStatistics", "get7DayHandlerTrend", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<JSONArray> getDataUploadTrend(String areaCode) {
        JSONObject params = new JSONObject();
        params.put("areaCode", areaCode);
        JSONArray bizObject = h3yunOperate.CustomInvokeArray("EventStatistics", "getDataUploadTrend", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<JSONObject> statW00000CountInfo(String areaCode) {
        JSONObject params = new JSONObject();
        params.put("areaCode", areaCode);
        JSONObject bizObject = h3yunOperate.CustomInvoke("RunDataStatistics", "statW00000CountInfo", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<JSONObject> statDisinfectantCountInfo(String areaCode) {
        JSONObject params = new JSONObject();
        params.put("areaCode", areaCode);
        JSONObject bizObject = h3yunOperate.CustomInvoke("RunDataStatistics", "statDisinfectantCountInfo", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<JSONObject> statSludgeCountInfo(String areaCode) {
        JSONObject params = new JSONObject();
        params.put("areaCode", areaCode);
        JSONObject bizObject = h3yunOperate.CustomInvoke("RunDataStatistics", "statSludgeCountInfo", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<JSONObject> statElectricityCountInfo(String areaCode) {
        JSONObject params = new JSONObject();
        params.put("areaCode", areaCode);
        JSONObject bizObject = h3yunOperate.CustomInvoke("RunDataStatistics", "statElectricityCountInfo", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public Result<JSONArray> getHospitalSensorData(JSONObject params) {
        JSONArray bizObject = h3yunOperate.CustomInvokeArray("SensorDataSearch", "getHospitalSensorData", params);
        return Result.success(bizObject, "ok");
    }

    @Override
    public void exportHospitalSensorData(JSONObject params, HttpServletResponse response) throws IOException {
        try {
            // 获取数据
            JSONArray dataArray = h3yunOperate.CustomInvokeArray("SensorDataSearch", "getHospitalSensorData", params);
            
            if (dataArray == null || dataArray.isEmpty()) {
                log.warn("导出数据为空");
                return;
            }

            // 转换为Excel数据模型
            List<HospitalSensorDataExcel> excelDataList = new ArrayList<>();
            for (int i = 0; i < dataArray.size(); i++) {
                JSONObject data = dataArray.getJSONObject(i);
                HospitalSensorDataExcel excelData = new HospitalSensorDataExcel();
                
                // 设置序号 - 从1开始递增
                excelData.setSerialNumber(i + 1);
                
                // 设置所属单位
                excelData.setOrganization(data.getString("所属单位"));
                
                // 设置监测时间
                excelData.setMonitorTime(data.getString("监测时间"));
                
                // 设置化学需氧量COD
                Object codValue = data.get("化学需氧量COD");
                if (codValue != null) {
                    excelData.setCod(new BigDecimal(codValue.toString()));
                }
                
                // 设置总余氯
                Object totalChlorineValue = data.get("总余氯");
                if (totalChlorineValue != null) {
                    excelData.setTotalChlorine(new BigDecimal(totalChlorineValue.toString()));
                }
                
                // 设置PH值
                Object phValue = data.get("PH值");
                if (phValue != null) {
                    excelData.setPh(new BigDecimal(phValue.toString()));
                }
                
                // 设置氨氮
                Object ammoniaNitrogenValue = data.get("氨氮");
                if (ammoniaNitrogenValue != null) {
                    excelData.setAmmoniaNitrogen(new BigDecimal(ammoniaNitrogenValue.toString()));
                }
                
                // 设置污水流量
                Object sewageFlowValue = data.get("污水流量");
                if (sewageFlowValue != null) {
                    excelData.setSewageFlow(new BigDecimal(sewageFlowValue.toString()));
                }
                
                // 设置流量均值
                Object flowAverageValue = data.get("流量均值");
                if (flowAverageValue != null) {
                    excelData.setFlowAverage(new BigDecimal(flowAverageValue.toString()));
                }
                
                excelDataList.add(excelData);
            }

            // 设置响应头
            String fileName = URLEncoder.encode("医院传感器数据", StandardCharsets.UTF_8.toString());
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 使用EasyExcel导出
            EasyExcel.write(response.getOutputStream(), HospitalSensorDataExcel.class)
                    .sheet("医院传感器数据")
                    .doWrite(excelDataList);

            log.info("医院传感器数据导出成功，共导出{}条记录", excelDataList.size());
            
        } catch (Exception e) {
            log.error("导出医院传感器数据失败", e);
            throw new IOException("导出失败：" + e.getMessage());
        }
    }

}